package com.eg366.nioLearn.baseSocket.chapter02.UDP;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPEchoServer {
	
	private static final int ECHOMAX = 255;
	
	public static void main(String[] args) throws IOException {
		args = new String[]{"5555"};
		if(args.length != 1) {
			throw new IllegalArgumentException("Parameter(s): <Port>");
		}
		/* 本地端口 */
		int sevPort = Integer.parseInt(args[0]);
		
		/* 创建数据报文套接字 */
		DatagramSocket socket = new DatagramSocket(sevPort);
		/* 创建数据报文 */
		DatagramPacket packet = new DatagramPacket(new byte[ECHOMAX], ECHOMAX);
		
		while(true) {
			/* receive方法将阻塞等待，直到接收到从客户端发来的数据报文（或超时）。接收到的数据包本身包含其发送者的源地址和端口号 */
			socket.receive(packet);
			System.out.println("Handling client at "
					+ packet.getAddress().getHostAddress() + " on port"
					+ packet.getPort());
			
			/* 数据报文中数据部分的内部长度 */
			System.out.println("Receive Data length:" + packet.getLength());
			byte[] desBuf = new byte[packet.getLength()];
			System.out.println("Receive DATA:" + new String(packet.getData()));
			System.arraycopy(packet.getData(), 0, desBuf, 0, desBuf.length);
			System.out.println("Receive Data:" + new String(desBuf));
			
			/* 发送回馈信息 */
			socket.send(packet);
			/* 重置数据包缓冲区大小；处理了接收到的消息后，数据包的内部长度将设置为刚处理过的消息的长度 */
			packet.setLength(ECHOMAX);
		}
	}
}
